package com.baitiaojun.web.config;

import com.baitiaojun.common.constants.WebFilterOrderEnum;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;


@Configuration
public class CorsConfiguration {

    @Bean
    public FilterRegistrationBean<CorsFilter> registerCorsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsFilter()); //该设置对所有请求路径生效
        FilterRegistrationBean<CorsFilter> filterRegistrationBean = new FilterRegistrationBean<>(new CorsFilter(source));
        filterRegistrationBean.setOrder(WebFilterOrderEnum.CORS_FILTER);
        return filterRegistrationBean;
    }

    /**
     * 跨域过滤器
     * @return
     */
    public org.springframework.web.cors.CorsConfiguration corsFilter() {
        org.springframework.web.cors.CorsConfiguration corsConfiguration = new org.springframework.web.cors.CorsConfiguration();
        corsConfiguration.setAllowCredentials(true); //打开认证许可
        corsConfiguration.addAllowedHeader("*"); //允许所有源请求头
        corsConfiguration.addAllowedMethod("*"); //允许所有源请求方法
        corsConfiguration.addAllowedOriginPattern("*"); //允许所有源请求地址
        corsConfiguration.setMaxAge(1800L); //对某个前端进行跨域访问的有效期是1800秒, 30分钟
        return corsConfiguration;
    }
}
